/*
 * N900ClientConnect.cpp
 *
 *  Created on: Aug 18, 2016
 *      Author: ubuntu
 */


#include "N900ClientConnect.h"
#include "N900Parse.h"
#include "N900DataInfo.h"
#include "../DBManager.h"
#include "../common.h"
#include "../Conf.h"
#include <assert.h>


N900ClientConnection::N900ClientConnection(TcpServer* parent, struct connectop *op, struct sockaddr *addr) :
	ClientConnection(parent, op, addr)
{
//	debug(LOG_DEBUG, "Create new client");
	min_len = N900_TAG_HEAD_LEN + N900_TAG_TAIL_LEN + 9;
	obdid = 0;
	pStatus = NULL;
}

N900ClientConnection::~N900ClientConnection()
{
//	debug(LOG_DEBUG, "Close connect");
}

bool N900ClientConnection::parsePackage(unsigned char *pBuf, size_t len, int add_head, int add_tail)
{
	unsigned char *buf = pBuf + add_head;
	if (memcmp(buf, N900_TAG_HEAD, N900_TAG_HEAD_LEN) != 0)
		return false;
	if (memcmp(buf+len-N900_TAG_TAIL_LEN, N900_TAG_TAIL, N900_TAG_TAIL_LEN) != 0)
		return false;
	if (len <= min_len)
		return false;
	N900DataInfo *pDataInfo = new N900DataInfo();
	pDataInfo->parse(pBuf, len, add_head, add_tail);
	if (obdid == 0 && pDataInfo->getObdid() == 0) {
		debug(LOG_DEBUG, "这有点不像话啊");
	} else if (obdid != 0 && pDataInfo->getObdid() == 0) {
		debug(LOG_DEBUG, "这个趋势不大好: 0 --> %u", obdid);
		pDataInfo->setObdid(obdid);
		buf[6] = (obdid >> 24) & 0xFF;
		buf[7] = (obdid >> 16) & 0xFF;
		buf[8] = (obdid >> 8) & 0xFF;
		buf[9] = obdid & 0xFF;
	} else if (obdid == 0 && pDataInfo->getObdid() != 0){
		obdid = pDataInfo->getObdid();
	}
	if (obdid > 1 && pStatus == NULL) {
		pStatus = (N900DevStatus *)m_pParent->find(&obdid);
		if (!pStatus) {
			pStatus = new N900DevStatus(obdid);
			m_pParent->add(pStatus);
		}
	}
	unsigned char resbuf[1024];
	int n;
	memset(resbuf, 0, sizeof(resbuf));
	if (m_fd > 0 && (n = pDataInfo->sendBuf(resbuf, buf, sizeof(resbuf), pStatus)) > 0)
		sendBuf(resbuf, n);
//	pDataInfo->debugInfo();
	if (obdid > 1) {
		char *tmp = (char *)malloc(len * 2+1);
		if (tmp) {
			for (size_t i = 0; i < len; i++)
				sprintf(tmp+i*2, "%02X", buf[i]);
			debug(LOG_DEBUG, "终端%u接收消息: [%s]", pDataInfo->getObdid(), tmp);
			free(tmp);
		}
		pushDataInfo(pDataInfo);
	} else {
		delete pDataInfo;
	}
	return true;
}
